package com.ruoyi.basic.controller;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.api.system.utils.ShiroUtils;
import com.ruoyi.api.system.utils.poi.ExcelUtil;
import com.ruoyi.basic.constant.BasicConstants;
import com.ruoyi.basic.domain.*;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basic.service.IBasicPostService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 专业技术职务Controller
 * 
 * @author ruoyi
 * @date 2021-12-06
 */
@Controller
@RequestMapping("/basic/post")
public class BasicPostController extends BaseController
{
    private String prefix = "basic/post";

    @Autowired
    private IBasicPostService basicPostService;

    @Autowired
    private IBasicUserService basicUserService;

    @RequiresPermissions("basic:post:view")
    @GetMapping()
    public String post(ModelMap mmap)
    {
        if(ShiroUtils.getSysUser().isAdmin() || ShiroUtils.getSubject().hasRole("administrator")){
            mmap.put("showFlag", true);
        }else{
            mmap.put("showFlag", false);
        }
        return prefix + "/post";
    }

    /**
     * 查询专业技术职务列表
     */
    @RequiresPermissions("basic:post:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasicPost basicPost)
    {
        startPage();
        if(!ShiroUtils.getSysUser().isAdmin() && !ShiroUtils.getSubject().hasRole("administrator")){
            basicPost.setIdCard(ShiroUtils.getLoginName());
        }
        List<BasicPost> list = basicPostService.selectBasicPostList(basicPost);
        return getDataTable(list);
    }

    /**
     * 导出员工技术职务
     */
    @RequiresPermissions("basic:post:export")
    @Log(title = "员工技术职务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BasicPost basicPost)
    {
        List<BasicPost> list = basicPostService.selectBasicPostList(basicPost);
        ExcelUtil<BasicPost> util = new ExcelUtil<BasicPost>(BasicPost.class);
        return util.exportExcel(list, "员工技术职务信息数据");
    }

    @Log(title = "员工技术职务", businessType = BusinessType.IMPORT)
    @RequiresPermissions("basic:post:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BasicPost> util = new ExcelUtil<BasicPost>(BasicPost.class);
        List<BasicPost> postList = util.importExcel(file.getInputStream());
        String message = basicPostService.importPost(postList, updateSupport, ShiroUtils.getLoginName());
        return AjaxResult.success(message);
    }

    @RequiresPermissions("basic:post:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<BasicPost> util = new ExcelUtil<BasicPost>(BasicPost.class);
        return util.importTemplateExcel("员工技术职务信息");
    }

    /**
     * 新增专业技术职务
     */
    @GetMapping("/add/{userId}")
    public String add(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        BasicUser user = basicUserService.selectBasicUserById(userId);
        mmap.put("user", user == null ? new BasicUser() : user);
        return prefix + "/add";
    }

    /**
     * 新增保存专业技术职务
     */
    @RequiresPermissions("basic:post:add")
    @Log(title = "专业技术职务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(required = false) MultipartFile file, BasicPost basicPost) throws IOException {
        if(!file.isEmpty()) {
            BasicUser basicUser = basicUserService.selectBasicUserById(basicPost.getUserId());
            String fileUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/post/" + basicUser.getIdCard(), file, false);
            basicPost.setFileUrl(fileUrl);
        }
        basicPost.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(basicPostService.insertBasicPost(basicPost));
    }

    /**
     * 修改专业技术职务
     */
    @GetMapping("/edit/{postId}")
    public String edit(@PathVariable("postId") Long postId, ModelMap mmap)
    {
        BasicPost basicPost = basicPostService.selectBasicPostByPostId(postId);
        mmap.put("basicPost", basicPost);
        return prefix + "/edit";
    }

    /**
     * 修改保存专业技术职务
     */
    @RequiresPermissions("basic:post:edit")
    @Log(title = "专业技术职务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile file, BasicPost basicPost) throws IOException {
        if(!file.isEmpty()) {
            BasicPost old = basicPostService.selectBasicPostByPostId(basicPost.getPostId());
            FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(old.getFileUrl(), Constants.RESOURCE_PREFIX));

            BasicUser basicUser = basicUserService.selectBasicUserById(basicPost.getUserId());
            String fileUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/post/" + basicUser.getIdCard(), file, false);
            basicPost.setFileUrl(fileUrl);
        }
        basicPost.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(basicPostService.updateBasicPost(basicPost));
    }

    /**
     * 删除专业技术职务
     */
    @RequiresPermissions("basic:post:remove")
    @Log(title = "专业技术职务", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(basicPostService.deleteBasicPostByPostIds(ids));
    }

    /**
     * 导出专业技术职务
     * @param postIds
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("basic:post:download")
    @Log(title = "专业技术职务", businessType = BusinessType.EXPORT)
    @GetMapping( "/download")
    public void download(String postIds, HttpServletResponse response) throws Exception
    {
        List<BasicPost> fileList = basicPostService.selectBasicPostByPostIds(postIds);
        String strZipPath = RuoYiConfig.getDownloadPath() + System.currentTimeMillis() + ".zip";
        ZipOutputStream out = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            ServletOutputStream outputStream = response.getOutputStream();
            for(BasicPost basicPost : fileList) {
                String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicPost.getFileUrl(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                out.putNextEntry(new ZipEntry(downloadName));
                fis = new FileInputStream(new File(downloadPath));
                byte[] b = new byte[1024];
                int length;
                while ((length = fis.read(b)) > 0)
                {
                    out.write(b, 0, length);
                }
                out.closeEntry();
            }
            out.close();
            bis = new BufferedInputStream(new FileInputStream(strZipPath));
            FileCopyUtils.copy(bis, outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.close(bis);
            IOUtils.close(fis);
            IOUtils.close(out);
        }
        FileUtils.deleteFile(strZipPath);
    }
}
